package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    /**
     * 根据父ID查询所有的分类
     *
     * @param pid
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByPid(Long pid) {
        // 根据父id查询到所有的分类信息
        List<Category> categories = query().eq("parent_id", pid).list();
        // 将category对象转成categoryDTO返回
        return CategoryDTO.convertEntityList(categories);
    }


    /**
     * 根据品牌ID查询该品牌下的所有分类
     */
    @Override
    public List<CategoryDTO> queryCategoryByBid(Long bid) {
        // 根据品牌查询到分类id
        List<CategoryBrand> brandList = categoryBrandService.query().eq("brand_id", bid).list();
        // 判断获取到的分类集合是否为空
        if (CollectionUtils.isEmpty(brandList)) {
            return Collections.emptyList();
        }
        // 获取category集合
        List<Long> categories = brandList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        // 根据分类id查询分类信息
        List<Category> categoryList = listByIds(categories);
        return CategoryDTO.convertEntityList(categoryList);


        // 直接多表查询
//        List<CategoryDTO> categories = baseMapper.queryCategoryByBid(bid);
//        return categories;
    }

    /**
     * 根据分类id查询所有的分类信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        List<Category> categories = listByIds(ids);
        return CategoryDTO.convertEntityList(categories);
    }

    /**
     * 根据分类id查询分类信息
     */
    @Override
    public List<CategoryDTO> queryCategoryByCid(Long id) {
        List<Category> categories = query().eq("id", id).list();
        return CategoryDTO.convertEntityList(categories);
    }


}
